<script setup lang="ts">
import { onMounted, onBeforeMount, onUnmounted } from 'vue';
import {
  getCurrentInstance,
  showLoading,
  showToast,
  connectSocket,
  getStorageSync,
  setNavigationBarTitle,
  closeSocket,
} from '@tarojs/taro';
import IMG_ICON_DEVICE_STATUS_OPEN from '/@/assets/image/icon/device-status-open.png';
import IMG_ICON_DEVICE_STATUS_CLOSE from '/@/assets/image/icon/device-status-close.png';
import IMG_ICON_DEVICE_LIGHT_OPEN from '/@/assets/image/icon/device-light-open.png';
import IMG_ICON_DEVICE_LIGHT_CLOSE from '/@/assets/image/icon/device-light-close.png';
import IMG_ICON_DEVICE_AIR_CONDITION_CLOSE from '/@/assets/image/icon/device-air-condition-close.png';
import IMG_ICON_DEVICE_AIR_CONDITION_OPEN from '/@/assets/image/icon/device-air-condition-open.png';
import IMG_ICON_DEVICE_ENTRANCE_GUARD_OPEN from '/@/assets/image/icon/device-entrance-guard-open.png';
import IMG_ICON_DEVICE_ENTRANCE_GUARD_CLOSE from '/@/assets/image/icon/device-entrance-guard-close.png';
import IMG_ICON_DEVICE_LOCK_CLOSE from '/@/assets/image/icon/device-lock-close.png';
import IMG_ICON_DEVICE_LOCK_OPEN from '/@/assets/image/icon/device-lock-open.png';
import { QUERY_SWITCH_STATUS_LIST } from '/@/api/modules/base/device-list';
import { CTRL_SWITCH_STATUS } from '/@/api/modules/base/device-detail';
import { state } from './state';
//当执行refresh()方法,会触发scrolltoupper和scrolltolower方法,导致queryList请求三次
//导致list数据重复
//isRefreshing 去掉重复请求
let isRefreshing = false;
/**
 * 设置设备的状态
 */
function switchDeviceStatus(item: AppSysDevice.SwitchStatus) {
  //智能锁，为了项目演示添加固定项，只在4F中显示
  if (item.deviceCategoryId === '8') {
    item.switchStatus = item.switchStatus === 1 ? 2 : 1;
    return;
  }

  let tag = item.pointTag;
  //定制化设备
  if (item.deviceCategoryId === '7' && item.deviceTypeId === '16') {
    tag = 'kgkz';
  }
  showLoading();
  console.log('CTRL_SWITCH_STATUS');
  CTRL_SWITCH_STATUS({
    deviceId: item.id,
    switchStatus: item.switchStatus === 1 ? 2 : 1,
    pointTag: tag,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showToast({ title: '设置成功', icon: 'success' });
      refreshList();
    } else {
      showToast({ title: '设置失败', icon: 'error' });
    }
  });
}

const params = getCurrentInstance().router?.params as {
  areaId: string;
  areaName: string;
};

/**
 * @description 消息列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  console.log('queryList');
  if (!page && state.finished) return;
  state.loading = true;
  isRefreshing = true;
  showLoading();
  QUERY_SWITCH_STATUS_LIST({
    comQuery: { page, pageSize },
    areaId: params.areaId,
    deviceCategoryIds: ['2', '5', '7'],
    deviceName: state.deviceName,
  })
    .then((res) => {
      state.loading = false;
      isRefreshing = false;
      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.content || !res.content.length) return;

      res.content.forEach((item) => state.list.push(item));
      addTestDevice();
      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
      isRefreshing = false;
    });
}

//智能锁，为了项目演示添加固定项，只在4F中显示
function addTestDevice() {
  if (state.list[0].areaId === '100005') {
    state.list.push({
      id: '889474249013534799',
      deviceName: '西企业业务用房门锁',
      areaId: '100005',
      areaName: '金华市公安局 / 江南分局 / 一号楼 / 4F',
      switchStatus: 2,
      deviceCategoryId: '8',
      deviceCategoryCode: '8',
      deviceCategoryName: '智能锁',
      deviceTypeCode: '17',
      deviceTypeId: '17',
      deviceTypeName: '智能锁',
      pointTag: '',
    });
  }
}

/**
 * @function 加载
 */
function onLoading() {
  console.log('onLoading');
  if (isRefreshing || state.finished) return;

  queryList(state.activePage);
}
/**
 * websocket同步设备状态
 */
function getWebsocket() {
  connectSocket({
    url: `ws:${
      process.env.APP_API_URL
    }ib/message/v1/websocket?labels=ib,admin&uauth=${getStorageSync('token')}`,
    success: function () {
      console.log('connect success');
    },
  }).then((task) => {
    task.onOpen(function () {
      console.log('onOpen');
      // task.send({ data: 'xxx' });
    });
    task.onMessage(function (msg) {
      console.log('onMessage: ', msg);
      const content: WebSocketApi.Dto = JSON.parse(msg.data);
      if (
        content.attachData?.msgType === 'devicePropertiesChange' &&
        content.attachData?.deviceSwitchStatusDto
      ) {
        const deviceItem: AppSysDevice.SwitchStatus = JSON.parse(
          content.attachData.deviceSwitchStatusDto,
        );
        state.list.forEach((item, index) => {
          if (item.id === deviceItem.id) {
            state.list[index] = deviceItem;
            console.log('deviceSwitch deviceItem: ', deviceItem);
          }
        });
      }
      //task.close({});
    });
    task.onError(function () {
      console.log('onError');
      //可以重新链接
    });
    task.onClose(function (e) {
      console.log('onClose: ', e);
    });
  });
}
onBeforeMount(() => {
  getWebsocket();
});

onMounted(() => {
  refreshList();
  setNavigationBarTitle({ title: decodeURI(params.areaName) });
});

onUnmounted(() => {
  closeSocket();
});

function refreshList() {
  console.log('refreshList');
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
}
</script>

<template>
  <view class="device-control-list app-page--1">
    <app-navbar :title="decodeURI(params.areaName)" />
    <nut-searchbar
      v-model="state.deviceName"
      placeholder="请输入设备名称"
      @search="refreshList()"
      @clear="
        () => {
          state.deviceName = '';
          refreshList();
        }
      "
    />
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="
        () => {
          console.log('scrolltolower');
          onLoading();
        }
      "
    >
      <view class="device-control-list__wrapper">
        <nut-grid
          v-if="state.list && state.list.length"
          column-num="2"
          :gutter="10"
          :border="false"
        >
          <nut-grid-item v-for="deviceItem in state.list" :key="deviceItem.id">
            <view class="device-control-item">
              <view class="device-control-item__header">
                <view class="device-control-item__device-name">{{ deviceItem.deviceName }}</view>
                <nut-avatar
                  shape="square"
                  bg-color="transparent"
                  @click.stop="switchDeviceStatus(deviceItem)"
                >
                  <image
                    :src="
                      deviceItem.switchStatus === 1
                        ? IMG_ICON_DEVICE_STATUS_OPEN
                        : IMG_ICON_DEVICE_STATUS_CLOSE
                    "
                  />
                </nut-avatar>
              </view>
              <!--门禁-->
              <view v-if="deviceItem.deviceCategoryId === '2'">
                <nut-avatar shape="square" bg-color="transparent">
                  <image
                    :src="
                      deviceItem.switchStatus === 1
                        ? IMG_ICON_DEVICE_ENTRANCE_GUARD_OPEN
                        : IMG_ICON_DEVICE_ENTRANCE_GUARD_CLOSE
                    "
                  />
                </nut-avatar>
              </view>
              <!--空调-->
              <view v-else-if="deviceItem.deviceCategoryId === '5'">
                <nut-avatar shape="square" bg-color="transparent">
                  <image
                    :src="
                      deviceItem.switchStatus === 1
                        ? IMG_ICON_DEVICE_AIR_CONDITION_OPEN
                        : IMG_ICON_DEVICE_AIR_CONDITION_CLOSE
                    "
                  />
                </nut-avatar>
              </view>
              <!--照明-->
              <view v-else-if="deviceItem.deviceCategoryId === '7'">
                <nut-avatar shape="square" bg-color="transparent">
                  <image
                    :src="
                      deviceItem.switchStatus === 1
                        ? IMG_ICON_DEVICE_LIGHT_OPEN
                        : IMG_ICON_DEVICE_LIGHT_CLOSE
                    "
                  />
                </nut-avatar>
              </view>
              <!-- 智能锁，为了项目演示添加固定项，只在4F中显示 -->
              <view v-else-if="deviceItem.deviceCategoryId === '8'">
                <nut-avatar shape="square" bg-color="transparent">
                  <image
                    :src="
                      deviceItem.switchStatus === 1
                        ? IMG_ICON_DEVICE_LOCK_OPEN
                        : IMG_ICON_DEVICE_LOCK_CLOSE
                    "
                  />
                </nut-avatar>
              </view>
            </view>
          </nut-grid-item>
        </nut-grid>
      </view>

      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
